import React, { Component } from "react";
import empty from "../../assets/images/empty.jpg";
import "./Cart.scss";
import { NavBar, Checkbox, Toast } from "antd-mobile";
import { withRouter } from "react-router-dom";
import emptyProduct from "../../assets/images/empty_product.jpg";

// import { withRouter } from "react-router-dom";
// import myaxios from "../../utils/myaxios";
// import axios from "axios"
class Cart extends Component {
  state = {
    carts: [], //购物车数据
    heji: "", //合计
    AllCheck: true, //全选
    GoodsNum: 0,
  };
  // 创建周期
  componentDidMount() {
    //获取本地缓存中的购物车数据
    let carts_str = localStorage.getItem("carts");
    let carts = JSON.parse(carts_str || "[]");
    //循环数据的价格
    let heji = 0;
    carts.forEach((v) => {
      heji += parseInt(v.goods_price);
    });
    //循环选中框
    let AllCheck = carts.every((v) => {
      return v.checked;
    });
    this.setState({
      carts,
      heji,
      AllCheck,
    });
    this.handelHeji();
  }

  // 处理单选框变化
  handleChekChange = (e) => {
    //获取本地缓存中的购物车数据
    let carts_str = localStorage.getItem("carts");
    let carts = JSON.parse(carts_str || "[]");
    //单选框改变
    carts[e.target.dataIndex].checked = e.target.checked;
    //循环选中框
    let AllCheck = carts.every((v) => {
      return v.checked;
    });
    this.setState({
      carts,
      AllCheck,
    });
    localStorage.setItem("carts", JSON.stringify(carts));
    this.handelHeji();
  };
  // 处理多选框变化
  handleAllChekChange = (e) => {
    //获取本地缓存中的购物车数据
    let carts_str = localStorage.getItem("carts");
    let carts = JSON.parse(carts_str || "[]");
    //循环单选框框
    carts.forEach((v) => {
      v.checked = e.target.checked;
    });
    this.setState({
      carts,
      AllCheck: !this.state.AllCheck,
    });
    localStorage.setItem("carts", JSON.stringify(carts));
    this.handelHeji();
  };
  // num操作
  handleNumClick = (payload) => {
    //获取本地缓存中的购物车数据
    let { num, id, act } = payload;
    let carts_str = localStorage.getItem("carts");
    let carts = JSON.parse(carts_str || "[]");
    if (act === "加") {
      carts[id].num = num + 1;
      this.setState({
        carts,
      });
      localStorage.setItem("carts", JSON.stringify(carts));
    } else if (act === "减") {
      if (num > 1) {
        carts[id].num = num - 1;
        this.setState({
          carts,
        });
        localStorage.setItem("carts", JSON.stringify(carts));
      }
      // else {
      //   confirm("确定要删除吗");
      //   if (confirm("确定要删除吗") == true) {
      //     carts.splice(id, 1);
      //     this.setState({
      //       carts,
      //     });
      //     localStorage.setItem("carts", JSON.stringify(carts));
      //   }
      // }
    }
    this.handelHeji();
  };
  // heji和 GoodsNum操作操作
  handelHeji = () => {
    let carts_str = localStorage.getItem("carts");
    let carts = JSON.parse(carts_str || "[]");
    let heji = 0;
    let GoodsNum = 0;
    //循环单选框框
    carts.forEach((v) => {
      if (v.checked) {
        heji += v.goods_price * v.num;
        GoodsNum += v.num;
      }
    });
    this.setState({
      heji,
      GoodsNum,
    });
  };
  //跳转至商品详情页面
  handleProductItemClick = (e) => {
    let goods_id = e.target.getAttribute("goods-id");
    if (goods_id) {
      this.props.history.push("/goodDetail/" + goods_id);
    }
  };
  // 立即购买
  pay = (params) => {
    let carts_str = localStorage.getItem("carts");
    let carts = JSON.parse(carts_str || "[]");
    let newCarts = [];
    carts.forEach((v, i) => {
      if (v.checked) {
        newCarts.push(carts[i]);
      }
    });
    if (newCarts.length === 0) {
      Toast.info("亲,你还没选择任何东西", 1);
    } else {
      localStorage.setItem("payitem", JSON.stringify(newCarts));
    }
    this.props.history.push({
      pathname: "/pay",
      state: { carts: this.state.carts },
    });
  };
  render() {
    return (
      <div className="yg-cart">
        {/* 如果没有加入商品开始 */}
        {!!this.state.carts.length ? (
          <div>
            {/* 购物车头部开始 */}
            <div className="yg-cart-nav">
              <NavBar className="cart-nav">优购商城</NavBar>
            </div>
            {/* 购物车头部结束 */}
            {/* 购物车开始 */}
            <div className="yg-cart-main" onClick={this.handleProductItemClick}>
              {this.state.carts.map((v, i) => {
                return (
                  <div className="cart-main-item" key={v.goods_id}>
                    <div className="cart-main-item-left">
                      <Checkbox
                        dataIndex={i}
                        onChange={this.handleChekChange}
                        checked={v.checked}
                      ></Checkbox>
                    </div>
                    <div className="cart-main-item-content">
                      <img
                        goods-id={v.goods_id}
                        src={
                          v.goods_small_logo ? v.goods_small_logo : emptyProduct
                        }
                        alt=""
                      />
                    </div>
                    <div className="cart-main-item-right">
                      <div goods-id={v.goods_id} className="item-right-title">
                        {v.goods_name}
                      </div>
                      <div className="item-right-price-num">
                        <div className="item-right-price">
                          ￥{v.goods_price}
                        </div>
                        <div className="item-right-num">
                          <i
                            className="iconfont icon-iconjian"
                            onClick={this.handleNumClick.bind(this, {
                              num: v.num,
                              id: i,
                              act: "减",
                            })}
                          ></i>
                          {v.num}
                          <i
                            className="iconfont icon-jia"
                            onClick={this.handleNumClick.bind(this, {
                              num: v.num,
                              id: i,
                              act: "加",
                            })}
                          ></i>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
            {/* 购物车结束 */}
            {/* 购物车结算开始 */}
            <div className="yg-cart-bottom">
              <label className="cart-bottom-left" htmlFor="">
                <Checkbox
                  onChange={this.handleAllChekChange}
                  checked={this.state.AllCheck}
                ></Checkbox>
                <span>全选</span>
              </label>
              <div className="cart-bottom-common">
                合计：<span>￥{this.state.heji}</span>
              </div>
              <div className="cart-bottom-right">
                <button onClick={this.pay}>
                  去结算({this.state.GoodsNum})
                </button>
              </div>
            </div>
            {/* 购物车结算结束 */}
          </div>
        ) : (
          <div>
            <div className="yg-cart-nav">
              <NavBar className="cart-nav">优购商城</NavBar>
            </div>
            <div className="yg-cart-empty">
              <img src={empty} className="cart-empty-img" alt="" />
              <h3 className="empty_text">
                <a href="#/category">去逛逛</a>
              </h3>
            </div>
          </div>
        )}
        {/* 如果没有加入商品结束 */}
      </div>
    );
  }
}
export default withRouter(Cart);
